const router = require('express').Router();
const itemModel = require('../models/item');
router.get('/home', (req,res) => {
  itemModel.find().sort({
    _id: -1
  }).then(re => {
    res.render('home', {
      items: re
    });
  }).catch(err =>{
    res.render('home', {
      items: []
    });
  })
  
})
// 删除商品的路由
router.get('/delItem', (req, res)=> {
  const { id } = req.query;
  itemModel.deleteOne({
    _id: id
  }).then(re => {
    res.send({
      code: 0,
      msg: '删除成功'
    })
  }).catch(err=> {
    res.send({
      code: -1,
      msg: '删除失败'
    })
  })
})
// 更新商品

router.post('/updateItem', (req, res)=> {
  const { id } = req.body;
  itemModel.updateOne(
    {
      _id: id
    },
    {
      itemStore: 100
    }
  ).then(re => {
    res.send({
      code: 0,
      msg: '更新成功'
    })
  }).catch(err=> {
    res.send({
      code: -1,
      msg: '更新失败'
    })
  })
})

// 新增商品
router.post('/addItem', (req, res) => {
  const { itemName, itemPrice, itemStore } = req.body;
  itemModel.insertMany({
    itemName,
    itemPrice,
    itemStore
  }).then(re => {
    res.send({
      code: 0,
      msg: '增加成功'
    })
  }).catch(err=> {
    res.send({
      code: -1,
      msg: '插入失败'
    })
  })
})
module.exports = router;